﻿using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Http;

namespace Core.Extensions;

public static class Base64ImageExtensions
{
    /// <summary>
    /// 将 Base64 图片字符串转换为 IFormFile。
    /// 支持 data:image/png;base64, 这样的前缀。
    /// </summary>
    /// <param name="base64String">Base64 图片字符串</param>
    /// <param name="fileName">文件名（默认随机名.png）</param>
    /// <returns>IFormFile 对象</returns>
    public static IFormFile ToFormFile(this string base64String, string? fileName = null)
    {
        if (string.IsNullOrWhiteSpace(base64String))
            throw new BoilerplateException(nameof(base64String), "Base64字符串不能为空");

        // 解析 MIME 类型
        var match = Regex.Match(base64String, @"^data:(?<type>image\/[a-zA-Z0-9.+-]+);base64,");
        var contentType = match.Success ? match.Groups["type"].Value : "image/png";

        // 移除 data:image/png;base64, 头部
        var cleaned = Regex.Replace(base64String, @"^data:image\/[a-zA-Z0-9.+-]+;base64,", string.Empty);

        // Base64 转字节
        byte[] bytes = Convert.FromBase64String(cleaned);

        // 生成默认文件名
        if (string.IsNullOrEmpty(fileName))
        {
            string ext = contentType switch
            {
                "image/jpeg" => ".jpg",
                "image/png" => ".png",
                "image/gif" => ".gif",
                "image/webp" => ".webp",
                _ => ".png"
            };
            fileName = $"{Guid.NewGuid():N}{ext}";
        }

        // 创建 IFormFile
        var stream = new MemoryStream(bytes);
        var formFile = new FormFile(stream, 0, bytes.Length, "file", fileName)
        {
            Headers = new HeaderDictionary(),
            ContentType = contentType
        };

        return formFile;
    }
}
